﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.BLL;
using WXYW.DAL;

namespace WXYW
{
    public partial class FillDOA : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindCustomerInfo();

                if (!string.IsNullOrEmpty(Request.QueryString["Insert"]))
                {
                    productListView.InsertItemPosition = InsertItemPosition.LastItem;
                }
                else
                {
                    productListView.InsertItemPosition = InsertItemPosition.None;
                }

                if (!string.IsNullOrEmpty(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]))
                {
                    BindApplicationProductList(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
                }
                else
                {
                    productListView.DataBind();
                }

                if (productListView.InsertItem != null)
                {
                    InitializeListViewItem(productListView.InsertItem);
                }

                ProviderTxtBox.Focus();
            }
        }

        protected void PreviewButton_Click(object sender, EventArgs e)
        {
            long applicationID = 0;
            // 有一个产品尚未提交
            if (productListView.InsertItem != null)
            {
                applicationID = InsertProduct();
            }
            // 没有未提交的产品
            else if (!string.IsNullOrEmpty(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]))
            {
                applicationID = Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
            }

            // 合法的Application, 转到预览页面
            if (applicationID > 0)
            {
                ApplicationService applicationService = new ApplicationService();
                ApplicationForm applicationForm = applicationService.GetApplicationFormDetailByID(applicationID);
                applicationForm.ProviderName = ProviderTxtBox.Text;
                if (applicationForm.RunningNumber == null)
                {
                    applicationForm.RunningNumber = RunningNumberService.GenerateApplicationNumber();
                }
                applicationService.UpdateApplication(applicationForm);

                Response.Redirect(string.Format("PreviewApplicationForm.aspx?Type=D&{0}={1}", Constants.QUERYSTR_APPLICATION_ID, applicationID));
            }
        }

        private void BindCustomerInfo()
        {
            applyCompanyNameTxtBox.Text = ContextService.CurrentAccount.FullName;
            mailAddressTxtBox.Text = ContextService.CurrentAccount.UserAddress;
            applierEmailTxtBox.Text = ContextService.CurrentAccount.UserEmail;
            applierFaxTxtBox.Text = ContextService.CurrentAccount.UserFax;
            applierMobilePhoneTxtBox.Text = ContextService.CurrentAccount.UserMobilePhone;
            applierNameTxtBox.Text = ContextService.CurrentAccount.ContactPerson;
            applierPhoneTxtBox.Text = ContextService.CurrentAccount.UserPhone;
        }

        private void BindApplicationProductList(string applicationID)
        {
            ApplicationService applicationService = new ApplicationService();
            ApplicationForm applicationForm = applicationService.GetApplicationFormDetailByID(long.Parse(applicationID));
            productListView.DataSource = applicationForm.ApplicationProduct.OrderBy(p => p.ApplicationProductID);
            productListView.DataBind();
            ProviderTxtBox.Text = applicationForm.ProviderName;
        }

        private void InitializeListViewItem(ListViewItem item)
        {
            ApplicationProductService productservice = new ApplicationProductService();

            DropDownList productClassDDL = (DropDownList)item.FindControl("ProductClassDDL");
            ProductClassService classService = new ProductClassService();
            productClassDDL.DataSource = classService.GetAllClassWithSelectOneByUser(ContextService.CurrentAccount);
            productClassDDL.DataTextField = "Name";
            productClassDDL.DataValueField = "ID";
            productClassDDL.DataBind();

            DropDownList productTypeDDL = (DropDownList)item.FindControl("DropDownList1");
            if (productTypeDDL != null)
            {
                productTypeDDL.Items.Add(new ListItem("请先选择产品分类", "0"));
            }

            ProblemTypeService problemtypeservice = new ProblemTypeService();
            DropDownList ddlproductProblemType = item.FindControl("DropDownList2") as DropDownList;
            ddlproductProblemType.Items.Clear();
            ddlproductProblemType.Items.Add("请选择故障类型");
            List<ProblemType> problemTypeList = problemtypeservice.GetAllProblemType();
            foreach (ProblemType type in problemTypeList)
            {
                ddlproductProblemType.Items.Add(new ListItem(type.Name, type.ID.ToString()));
            }

            DropDownList versionDDL = item.FindControl("VersionNumberDDL") as DropDownList;
            versionDDL.DataSource = classService.GetVersionsWithSelectOne();
            versionDDL.DataTextField = "Name";
            versionDDL.DataValueField = "Name";
            versionDDL.DataBind();
        }

        protected void productListView_ItemCanceling(object sender, ListViewCancelEventArgs e)
        {
            productListView.EditIndex = -1;
            productListView.InsertItemPosition = InsertItemPosition.None;
            BindApplicationProductList(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
        }

        protected void productListView_ItemInserting(object sender, ListViewInsertEventArgs e)
        {
        }

        protected void productListView_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            UpdateProduct();
        }

        protected void productListView_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            //productListView.InsertItemPosition = InsertItemPosition.None;
            productListView.EditIndex = e.NewEditIndex;
            BindApplicationProductList(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);

            InitializeListViewItem(productListView.EditItem);

            DropDownList ddlType = productListView.EditItem.FindControl("ProductTypeDDL") as DropDownList;
            DropDownList productClassDDL = (DropDownList)productListView.EditItem.FindControl("ProductClassDDL");
            DropDownList ddlproblemType = productListView.EditItem.FindControl("DropDownList2") as DropDownList;
            DropDownList ddlrepairType = productListView.EditItem.FindControl("DropDownList3") as DropDownList;
            DropDownList txtVersionNumber = (DropDownList)productListView.EditItem.FindControl("VersionNumberDDL");
            string productID = ((HiddenField)productListView.EditItem.FindControl("ProductID")).Value;
            ApplicationProductService productService = new ApplicationProductService();
            ApplicationProduct product = productService.GetApplicationProductByID(Convert.ToInt64(productID));
            if (!product.ProductTypeReference.IsLoaded)
            {
                product.ProductTypeReference.Load();
            }
            if (!product.ProblemTypeReference.IsLoaded)
            {
                product.ProblemTypeReference.Load();
            }
            if (!product.ProductType.ProductClassReference.IsLoaded)
            {
                product.ProductType.ProductClassReference.Load();
            }

            productClassDDL.SelectedValue = product.ProductType.ProductClass.ID.ToString();
            ProductClassService classService = new ProductClassService();
            ddlType.DataSource = classService.GetTypeListWithSelectOne(Convert.ToInt32(productClassDDL.SelectedValue));
            ddlType.DataTextField = "ProductTypeName";
            ddlType.DataValueField = "ProductTypeID";
            ddlType.DataBind();
            ddlType.SelectedValue = product.ProductType.ProductTypeID.ToString();
            ddlproblemType.SelectedValue = product.ProblemType.ID.ToString();
            ddlrepairType.SelectedValue = product.ProductRepairType;
            txtVersionNumber.SelectedValue = product.ProductVersionNumber;

            if (productListView.InsertItem != null)
            {
                InitializeListViewItem(productListView.InsertItem);
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string productID = ((Button)sender).CommandArgument;
            ApplicationProductService service = new ApplicationProductService();
            service.DeleteProduct(long.Parse(productID));
            BindApplicationProductList(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
        }

        protected void deleteInsertItemBtn_Click(object sender, EventArgs e)
        {
            if (productListView.Items.Count > 0)
            {
                Response.Redirect(string.Format("FillDOA.aspx?{0}={1}", Constants.QUERYSTR_APPLICATION_ID, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "TipMessage", "alert('至少需要保留一个产品，无法删除。');", true);
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (productListView.InsertItem != null)
            {
                long applicationID = InsertProduct();
                if (applicationID != 0)
                {
                    Response.Redirect(string.Format("FillDOA.aspx?Insert=1&{0}={1}", Constants.QUERYSTR_APPLICATION_ID, applicationID));
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]))
                {
                    Response.Redirect(string.Format("FillDOA.aspx?Insert=1&{0}={1}", Constants.QUERYSTR_APPLICATION_ID, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                }
                else
                {
                    Response.Redirect("FillDOA.aspx?Insert=1");
                }
            }
        }

        private long InsertProduct()
        {
            long applicationID = 0;

            // 读取插入信息
            DropDownList ddlProductType = (DropDownList)productListView.InsertItem.FindControl("DropDownList1");
            TextBox txtSerialNumber = (TextBox)productListView.InsertItem.FindControl("TextBox2");
            DropDownList ddlProblemType = (DropDownList)productListView.InsertItem.FindControl("DropDownList2");
            TextBox txtProblemDescription = (TextBox)productListView.InsertItem.FindControl("TextBox3");
            TextBox txtAppearance = (TextBox)productListView.InsertItem.FindControl("TextBox4");
            TextBox txtPurchseTime = (TextBox)productListView.InsertItem.FindControl("TextBox5");
            DropDownList txtVersionNumber = (DropDownList)productListView.InsertItem.FindControl("VersionNumberDDL");
            // 验证信息是否完整
            string validateStr = CheckProductRequiredField(ddlProductType, txtSerialNumber, ddlProblemType, txtProblemDescription,
                txtAppearance, txtPurchseTime, txtVersionNumber);
            if (string.IsNullOrEmpty(validateStr))
            {
                ApplicationService applicationService = new ApplicationService();
                // Application已经创建
                if (!string.IsNullOrEmpty(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]))
                {
                    ApplicationProductService productservice = new ApplicationProductService();
                    ProblemTypeService problemtypeservice = new ProblemTypeService();
                    ApplicationProduct product = new ApplicationProduct
                    {
                        ProductType = productservice.GetProducTypetByID(Convert.ToInt32(ddlProductType.SelectedValue)),
                        //ProductCount = Convert.ToInt32(((TextBox)productListView.InsertItem.FindControl("TextBox1")).Text),
                        ProductCount = 1,
                        ProductSerialNumber = txtSerialNumber.Text,
                        ProblemType = problemtypeservice.GetTypeByID(Convert.ToInt32(ddlProblemType.SelectedValue)),
                        ProductProblemDescription = txtProblemDescription.Text,
                        ProductAppearance = txtAppearance.Text,
                        ProductPurchaseDateTime = Convert.ToDateTime(txtPurchseTime.Text),
                        ProductRepairType = ((DropDownList)productListView.InsertItem.FindControl("DropDownList3")).Text,
                        ProductVersionNumber = txtVersionNumber.SelectedValue
                    };

                    ApplicationForm applicationForm = applicationService.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                    applicationForm.ProviderName = ProviderTxtBox.Text;
                    applicationForm.ApplicationProduct.Add(product);
                    applicationService.UpdateApplication(applicationForm);
                    applicationID = applicationForm.ApplicationID;
                }
                // Application尚未创建
                else
                {
                    ApplicationForm applicationForm = new ApplicationForm();
                    applicationForm.ApplicationDateTime = DateTime.Now;
                    applicationForm.ApplicationType = "D";
                    applicationForm.IsSubmit = false;
                    applicationForm.Status = "等待RMA单号确认";
                    UserService userService = new UserService();
                    applicationForm.User = userService.GetUserByID(ContextService.CurrentAccount.UserID);
                    ProviderService providerService = new ProviderService();
                    applicationForm.ProviderName = ProviderTxtBox.Text;

                    ApplicationProductService productservice = new ApplicationProductService();
                    ProblemTypeService problemtypeservice = new ProblemTypeService();
                    ApplicationProduct product = new ApplicationProduct
                    {
                        ProductType = productservice.GetProducTypetByID(Convert.ToInt32(ddlProductType.SelectedValue)),
                        ProductCount = 1,
                        ProductSerialNumber = txtSerialNumber.Text,
                        ProductVersionNumber = txtVersionNumber.Text,
                        ProblemType = problemtypeservice.GetTypeByID(Convert.ToInt32(ddlProblemType.SelectedValue)),
                        ProductProblemDescription = txtProblemDescription.Text,
                        ProductAppearance = txtAppearance.Text,
                        ProductPurchaseDateTime = Convert.ToDateTime(txtPurchseTime.Text),
                        ProductRepairType = ((DropDownList)productListView.InsertItem.FindControl("DropDownList3")).Text
                    };
                    applicationForm.ApplicationProduct.Add(product);
                    applicationService.AddApplication(applicationForm);
                    applicationID = applicationForm.ApplicationID;
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('" + validateStr + "');", true);
            }
            return applicationID;
        }

        private void UpdateProduct()
        {
            DropDownList ddlProductType = (DropDownList)productListView.EditItem.FindControl("ProductTypeDDL");
            TextBox txtSerialNumber = (TextBox)productListView.EditItem.FindControl("TextBox2");
            DropDownList ddlProblemType = (DropDownList)productListView.EditItem.FindControl("DropDownList2");
            TextBox txtProblemDescription = (TextBox)productListView.EditItem.FindControl("TextBox3");
            TextBox txtAppearance = (TextBox)productListView.EditItem.FindControl("TextBox4");
            TextBox txtPurchseTime = (TextBox)productListView.EditItem.FindControl("TextBox5");
            DropDownList txtVersionNumber = (DropDownList)productListView.EditItem.FindControl("VersionNumberDDL");

            string validateStr = CheckProductRequiredField(ddlProductType, txtSerialNumber, ddlProblemType, txtProblemDescription, 
                txtAppearance, txtPurchseTime, txtVersionNumber);
            if (string.IsNullOrEmpty(validateStr))
            {
                ApplicationProductService productservice = new ApplicationProductService();
                ProblemTypeService problemtypeservice = new ProblemTypeService();
                string productID = ((HiddenField)productListView.EditItem.FindControl("ProductID")).Value;
                ApplicationProduct product = productservice.GetApplicationProductByID(long.Parse(productID));
                product.ProductType = productservice.GetProducTypetByID(Convert.ToInt32(ddlProductType.SelectedValue));
                product.ProductCount = 1;
                product.ProductSerialNumber = txtSerialNumber.Text;
                product.ProductVersionNumber = txtVersionNumber.SelectedValue;
                product.ProblemType = problemtypeservice.GetTypeByID(Convert.ToInt32(ddlProblemType.SelectedValue));
                product.ProductProblemDescription = txtProblemDescription.Text;
                product.ProductAppearance = txtAppearance.Text;
                product.ProductPurchaseDateTime = Convert.ToDateTime(txtPurchseTime.Text);
                product.ProductRepairType = ((DropDownList)productListView.EditItem.FindControl("DropDownList3")).Text;
                productservice.UpdateProduct(product);
                productListView.EditIndex = -1;
                //productListView.InsertItemPosition = InsertItemPosition.LastItem;
                BindApplicationProductList(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('" + validateStr + "');", true);
            }

            if (productListView.InsertItem != null)
            {
                InitializeListViewItem(productListView.InsertItem);
            }
        }

        private string CheckProductRequiredField(DropDownList ddlProductType, TextBox txtSerialNumber, DropDownList ddlProblemType,
            TextBox txtProblemDescription, TextBox txtAppearance, TextBox txtPurchseTime, DropDownList txtVersionNumber)
        {
            string validStr = string.Empty;
            if (ddlProductType.SelectedIndex == 0)
            {
                validStr += "请选择产品类型；";
            }
            if (string.IsNullOrEmpty(txtSerialNumber.Text))
            {
                validStr += "请输入产品型号； ";
            }
            if (txtSerialNumber.Text.Length > 250)
            {
                validStr += "产品型号的长度超过了最大限制250个字符；";
            }
            if (ddlProblemType.SelectedIndex == 0)
            {
                validStr += "请选择故障类型； ";
            }
            if (string.IsNullOrEmpty(txtProblemDescription.Text))
            {
                validStr += "请输入故障描述；";
            }
            if (string.IsNullOrEmpty(txtPurchseTime.Text))
            {
                validStr += "请输入购买时间；";
            }
            if (txtVersionNumber.SelectedValue.Equals("请选择"))
            {
                validStr += "请选择版本号。";
            }
            return validStr;
        }

        private bool AllFiledsOfInsertItemEmpty(DropDownList ddlProductType, TextBox txtSerialNumber, DropDownList ddlProblemType, TextBox txtProblemDescription, TextBox txtAppearance, TextBox txtPurchseTime)
        {
            if (ddlProductType.SelectedIndex > 0 || !string.IsNullOrEmpty(txtSerialNumber.Text) || ddlProblemType.SelectedIndex > 0 ||
                !string.IsNullOrEmpty(txtProblemDescription.Text) || !string.IsNullOrEmpty(txtPurchseTime.Text))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        protected void ProductClassDDLInsert_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList productClassDDL = ((DropDownList)productListView.InsertItem.FindControl("ProductClassDDL"));
            DropDownList productTypeDDL = ((DropDownList)productListView.InsertItem.FindControl("DropDownList1"));
            if (!productClassDDL.SelectedValue.Equals("0"))
            {
                ProductClassService classService = new ProductClassService();
                productTypeDDL.DataSource = classService.GetTypeListWithSelectOne(Convert.ToInt32(productClassDDL.SelectedValue));
                productTypeDDL.DataTextField = "ProductTypeName";
                productTypeDDL.DataValueField = "ProductTypeID";
                productTypeDDL.DataBind();
            }
            else
            {
                productTypeDDL.Items.Clear();
                productTypeDDL.Items.Add(new ListItem("请先选择产品分类", "0"));
            }
        }

        protected void ProductClassDDLEdit_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList productClassDDL = ((DropDownList)productListView.EditItem.FindControl("ProductClassDDL"));
            DropDownList productTypeDDL = ((DropDownList)productListView.EditItem.FindControl("ProductTypeDDL"));
            if (!productClassDDL.SelectedValue.Equals("0"))
            {
                ProductClassService classService = new ProductClassService();
                productTypeDDL.DataSource = classService.GetTypeListWithSelectOne(Convert.ToInt32(productClassDDL.SelectedValue));
                productTypeDDL.DataTextField = "ProductTypeName";
                productTypeDDL.DataValueField = "ProductTypeID";
                productTypeDDL.DataBind();
            }
            else
            {
                productTypeDDL.Items.Clear();
                productTypeDDL.Items.Add(new ListItem("请先选择产品分类", "0"));
            }
        }
    }
}
